package com.hx;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint(value = "/socket.io")//类似于 @GetMapping("/list")
public class ChatServer {

    private static Map<String,Session> routeTab = new HashMap<>();

    @OnOpen
    public void onOpen( Session session) throws IOException {
        System.out.println(session.getId());
    }

    @OnClose
    public void onClose(@PathParam("userId") String userId) throws IOException {
        routeTab.remove(userId);
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        for (String s : routeTab.keySet()) {
            Session session = routeTab.get(s);
            session.getBasicRemote().sendText(message);
        }
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }
}